//
//  AutoCheckViewModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/26/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.


import Foundation

typealias AutoCheckCellConfigurator = TableCellConfigurator<AutoCheckCell, AutoCheckViewModel.AutoCheckCellItem?>
typealias AutoCheckInfoCellConfigurator = TableCellConfigurator<AutoCheckInfoCell, AutoCheckViewModel.AutoCheckInfoItem?>


final class AutoCheckViewModel {
    
    struct AutoCheckSection {
        var name: String = ""
        var items: [CellConfigurator] = []
    }
    
    struct AutoCheckCellItem {
        var hint: String
        var value: String
    }
    
    struct AutoCheckInfoItem {
        var isDTP: Bool
        var data: [String: String]
        var isEmpty: Bool = false
    }
    
    struct OrderDetails: Decodable {
        var price: Int
        var orderID: String
    }
    
    struct Id: Decodable {
        var id: Int
    }
    
    var delegate: ViewModelProtocol!
    
    var currentData: AutoCheck!
    
    var data:[AutoCheckSection] = []
    
    private let backend = Backend()
}

extension AutoCheckViewModel {
    
    func loadCheckAuto (vin: String) {
        let request = URLRequest(url: Request(base: .garage).getUrl(path: "checkauto/m_presearch/\(vin)/"))
        delegate.updateSpinner(showSpinner: true)
        backend.fetchFromBackend(for: AutoCheck.self, request: request, statusCode: 200, sendBool: false) { (result) in
            self.delegate.updateSpinner(showSpinner: false)
            switch result {
                case .failure(let err):
                    self.delegate.didHappenError(error: err)
                case .success(let data):
                    self.fillData(data: data)
            }
        }
    }
    
    private func fillData (data: AutoCheck) {
        
        var sectionData = [
            AutoCheckSection(name: "Автомобиль",
                         items: [
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Марка", value: data.mark)),
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Модель", value: data.model))
            ])
        ]
        
        if let characteristics = data.data {
            sectionData.append(self.addCharacteristics(characteristics: characteristics))
        }
        
        if data.history_number > data.dtp_number {
            sectionData.append(self.addHistoryCells(count: data.history_number))
            sectionData.append(self.addDTPCells(count: data.dtp_number))
        } else {
            sectionData.append(self.addDTPCells(count: data.dtp_number))
            sectionData.append(self.addHistoryCells(count: data.history_number))
        }
        
        self.data = sectionData
        self.delegate.updatePosts()
    }
    
    private func addCharacteristics (characteristics: CarGeneralData) -> AutoCheckSection {
        return AutoCheckSection(name: "Характеристики",
                         items: [
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Вид транспортного средства", value: characteristics.vehicle_category)),
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Страна производитель", value: characteristics.origin_country)),
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Цвет", value: characteristics.color)),
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Объем двигателя, куб.см", value: characteristics.engine_volume)),
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Мощность мотора, л.с.", value: characteristics.engine_power_kwt)),
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Масса, кг", value: characteristics.empty_weight)),
                            AutoCheckCellConfigurator(item: AutoCheckCellItem(hint: "Допустимая полная масса, кг", value: characteristics.plated_weight))
        ])
    }
    
    private func addDTPCells (count: Int) -> AutoCheckSection {
        if count != 3 {
            var historyCells: [AutoCheckInfoCellConfigurator] = []
            for _ in 1...3 {
                historyCells.append(AutoCheckInfoCellConfigurator(item: AutoCheckInfoItem(isDTP: true, data: ["Описание": "********", "Дата снятия": "********"])))
            }
            return AutoCheckSection(name: "Данные о ДТП", items: historyCells)
        } else {
            return AutoCheckSection(name: "Данные о ДТП", items: [AutoCheckInfoCellConfigurator(item: AutoCheckInfoItem(isDTP: true, data: [:], isEmpty: true))])
        }
    }
    
    private func addHistoryCells (count: Int) -> AutoCheckSection {
        if count != 0 {
            var historyCells: [AutoCheckInfoCellConfigurator] = []
            for _ in 1...count {
                historyCells.append(AutoCheckInfoCellConfigurator(item: AutoCheckInfoItem(isDTP: false, data: ["Действие": "********","Тип": "********", "Дата снятия": "********"])))
            }
            
            return AutoCheckSection(name: "История перерегистрации", items: historyCells)
        } else {
            return AutoCheckSection(name: "История перерегистрации", items: [AutoCheckInfoCellConfigurator(item: AutoCheckInfoItem(isDTP: false, data: [:], isEmpty: true))])
        }
    }
}









// MARK: - Did not finish

extension AutoCheckViewModel {
    func loadOrderDetails (vin: String, completion: @escaping (Result<OrderDetails, RequestError>) -> Void) {
        
    }
    
    func postOrder (vin: String, completion: @escaping (Result<Id, RequestError>) -> Void) {
        var request = URLRequest(url: Request(base: .garage).getUrl(path: "checkauto/orders/"))
        request.httpMethod = "POST"
        
        let body:[String:Any] = [:]
        
        //"vin": vin, "include_dtp": true, "include_history": true
        
        backend.fetchFromBackend(for: Id.self, request: self.createRequest(request: request, data: body), statusCode: 201, sendBool: false) { (result) in
            switch result {
            case .failure(let err):
                completion(.failure(err))
            case .success(let id):
                completion(.success(id))
            }
        }
    }
    
    
    private func createRequest (request: URLRequest, data: [String: Any]) -> URLRequest {
        var _request = request
        
        if let json = try? JSONSerialization.data(withJSONObject: data, options: []) {
            _request.httpBody = json
        }
        
        return _request
    }
}
